package zunge.twitterdel.bean;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

public class TweetTimeDAO {
	private BeanFactory<TweetTime> factory;
	private BeanTable<TweetTime> tweetTable;
	static String jdbcDriver = "com.mysql.jdbc.Driver";
	
	public TweetTimeDAO(String jdbcURL, String userName, String password, String tableName) throws DAOException {
		try{
			tweetTable = BeanTable.getSQLInstance(TweetTime.class, tableName,
					jdbcDriver, jdbcURL, userName, password);
			if (!tweetTable.exists()) tweetTable.create("tweetID");

			tweetTable.setIdleConnectionCleanup(true);
			factory = tweetTable.getFactory();
		}catch (BeanFactoryException e) {throw new DAOException(e);}
	}
	
	public void create(TweetTime tweetTime) throws DAOException{
		try{
			
			Transaction.begin();
			TweetTime tweetTimeDB = factory.create(tweetTime.getTweetID());
			factory.copyInto(tweetTime, tweetTimeDB);
			Transaction.commit();
			
		}catch(RollbackException e){throw new DAOException(e);
		}finally{
			if(Transaction.isActive()){
				Transaction.rollback();
			}
		}
	}
}
